package com.asdc.springcloud.controller;

import com.asdc.springcloud.entities.CommonResult;
import com.asdc.springcloud.entities.Payment;

import com.asdc.springcloud.lb.MyLoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    //public static final String BASE_URL = "http://localhost:8001";
    public static final String BASE_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MyLoadBalance myLoadBalance;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/consumer/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        return restTemplate.postForObject(BASE_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(BASE_URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/consumer/getPaymentForEntity/get/{id}")
    public CommonResult<Payment> getPaymentForEntity(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(BASE_URL + "/payment/get/" + id, CommonResult.class);
        if (forEntity.getStatusCode().is2xxSuccessful()) {
            return forEntity.getBody();
        } else {
            return new CommonResult<>(44, "查询失败");
        }
    }


    @GetMapping("/consumer/getPaymentMyLoadBalance/get/{id}")
    public ResponseEntity<String> getPaymentMyLoadBalance(@PathVariable("id") Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances == null || instances.size() <= 0)
        {
            return null;
        }
        ServiceInstance serviceInstance = myLoadBalance.servinceInstence(instances);
        URI uri = serviceInstance.getUri();
        System.out.println("uri:===="+uri);
        //return restTemplate.getForObject(uri + "/getPaymentMyLoadBalance/get/" + id, CommonResult.class);
        return  restTemplate.getForEntity(uri + "/payment/get/" + id, String.class);
    }


}
